package com.x.compute.common.function;

import com.googlecode.aviator.lexer.token.OperatorType;
import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.type.AviatorBoolean;
import com.googlecode.aviator.runtime.type.AviatorJavaType;
import com.googlecode.aviator.runtime.type.AviatorObject;
import com.googlecode.aviator.runtime.type.AviatorType;

import java.math.BigDecimal;
import java.util.Map;

/**
 * 基本运算函数OperatorType.EQ(">=")的重载
 *
 * @author xuxin
 */
public class GeFunction extends AbstractFunction {

    @Override
    public String getName() {
        return OperatorType.GE.token;
    }

    /**
     * 函数处理逻辑
     *
     * @param env  变量上下文
     * @param arg1 参数对象1
     * @param arg2 参数对象2
     * @return
     */
    @Override
    public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2) {
        BigDecimal left = handle(env, arg1);
        BigDecimal right = handle(env, arg2);
        return AviatorBoolean.valueOf(left.compareTo(right) >= 0);
    }

    /**
     * 变量值处理
     *
     * @param env 变量上下文
     * @param arg 参数对象
     * @return
     */
    private BigDecimal handle(Map<String, Object> env, AviatorObject arg) {
        Object value = arg.getValue(env);
        value = value == null && arg.getAviatorType() == AviatorType.JavaType ? ((AviatorJavaType) arg).getName() : value;
        if (value != null) {
            return new BigDecimal(value.toString());
        }
        return null;
    }
}
